package controller

import (
	"admin/model"
	"common/helper"
	"fmt"
	"strings"
	"time"

	"github.com/valyala/fasthttp"
)

type SmsRecordController struct{}

// List 验证码列表
func (that *SmsRecordController) List(ctx *fasthttp.RequestCtx) {

	page := ctx.QueryArgs().GetUintOrZero("page")
	pageSize := ctx.QueryArgs().GetUintOrZero("page_size")
	phone := string(ctx.QueryArgs().Peek("phone"))
	state := ctx.QueryArgs().GetUintOrZero("state")
	startTime := string(ctx.QueryArgs().Peek("start_time"))
	endTime := string(ctx.QueryArgs().Peek("end_time"))

	if page < 1 {
		page = 1
	}
	if pageSize < 10 {
		pageSize = 10
	}
	if pageSize > 100 {
		pageSize = 100
	}

	filter := "ty = 1"
	//// 手机号校验
	if phone != "" {
		if !helper.CtypeDigit(phone) {
			helper.RetData(ctx, false, helper.PhoneFMTErr)
			return
		} else {
			filter += fmt.Sprintf(" AND phone = %s", phone)
		}
	}

	if state > 0 {
		filter += fmt.Sprintf(" AND state = %d", state)
	}

	st, err := time.ParseInLocation("2006-01-02 15:04:05", startTime, time.Local)
	if err != nil {
		helper.RetData(ctx, false, helper.DateTimeErr)
		return
	}
	et, err := time.ParseInLocation("2006-01-02 15:04:05", endTime, time.Local)
	if err != nil {
		helper.RetData(ctx, false, helper.DateTimeErr)
		return
	}

	filter += fmt.Sprintf(" AND create_at >= %d AND create_at < %d", st.Unix(), et.Unix())

	data, err := model.SmsList(page, pageSize, filter)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	helper.RetData(ctx, true, data)

}

// List 验证码列表
func (that *SmsRecordController) EmailList(ctx *fasthttp.RequestCtx) {

	page := ctx.QueryArgs().GetUintOrZero("page")
	pageSize := ctx.QueryArgs().GetUintOrZero("page_size")
	mail := string(ctx.QueryArgs().Peek("mail"))
	state := ctx.QueryArgs().GetUintOrZero("state")
	startTime := string(ctx.QueryArgs().Peek("start_time"))
	endTime := string(ctx.QueryArgs().Peek("end_time"))

	if page < 1 {
		page = 1
	}
	if pageSize < 10 {
		pageSize = 10
	}
	if pageSize > 100 {
		pageSize = 100
	}

	filter := "ty = 2"
	//// 手机号校验
	if mail != "" {
		if !strings.Contains(mail, "@") {
			helper.RetData(ctx, false, helper.EmailFMTErr)
			return
		} else {
			filter += fmt.Sprintf(" AND phone = %s", mail)
		}
	}

	if state > 0 {
		filter += fmt.Sprintf(" AND state = %d", state)
	}

	st, err := time.ParseInLocation("2006-01-02 15:04:05", startTime, time.Local)
	if err != nil {
		helper.RetData(ctx, false, helper.DateTimeErr)
		return
	}
	et, err := time.ParseInLocation("2006-01-02 15:04:05", endTime, time.Local)
	if err != nil {
		helper.RetData(ctx, false, helper.DateTimeErr)
		return
	}

	filter += fmt.Sprintf(" AND create_at >= %d AND create_at < %d", st.Unix(), et.Unix())

	data, err := model.SmsList(page, pageSize, filter)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	helper.RetData(ctx, true, data)
}
